import Big from 'big.js'
import { ElMessageBox } from 'element-plus'

/**
 * 格式化时间
 */
export const formatTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
export const formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 清除详情富文本自带样式
 */
export const formatHtml = (content) => {
  if (!content) {
    return ''
  }
  content = content.replace(/<!--(.+)-->/gi, '')
  content = content.replace(/class=/gi, 'sss=')
  content = content.replace(/<p/gi, '<p style="max-width:100% !important;word-wrap:break-word;word-break:break-word;" ')
  content = content.replace(/<img/gi, '<img style="max-width:100% !important;margin:0;display:inline-block !important; vertical-align:middle;" ')
  content = content.replace(/style="/gi, 'style="max-width:100% !important;table-layout:fixed;word-wrap:break-word;word-break:break-word;')
  content = content.replace(/<table/gi, '<table style="table-layout:fixed;word-wrap:break-word;word-break:break-word;" ')
  content = content.replace(/<td/gi, '<td cellspacing="0" cellpadding="0" style="border-width:1px; border-style:solid; border-color:#666; margin: 0px; padding: 0px;"')
  content = content.replace(/<video/gi, '<video style="width:100% !important;height:auto !important;margin:0;display:flex;" ')
  return content
}

/**
 * 根据相隔时间戳，计算相隔时间
 */
export const betweenTime = (betweenTimestamp) => {
  // 正的时间还是负的时间
  let signs = 1
  if (betweenTimestamp < 0) {
    betweenTimestamp = -betweenTimestamp
    signs = 0
  }

  if (betweenTimestamp > 1000) {
    const time = betweenTimestamp / 1000
    // 获取天、时、分、秒
    const day = parseInt(time / (60 * 60 * 24))
    const hou = parseInt(time % (60 * 60 * 24) / 3600)
    const min = parseInt(time % (60 * 60 * 24) % 3600 / 60)
    const sec = parseInt(time % (60 * 60 * 24) % 3600 % 60)
    return {
      day: `${timeFormat(day)}`,
      hou: `${timeFormat(hou)}`,
      min: `${timeFormat(min)}`,
      sec: `${timeFormat(sec)}`,
      signs
    }
  }
  return {
    day: '00',
    hou: '00',
    min: '00',
    sec: '00',
    signs
  }
}
const timeFormat = (times) => {
  return times < 10 ? '0' + times : times
}

/**
 * 计算相隔时间戳
 */
export const betweenTimestamp = (startTime, endTime) => {
  const newTime = new Date().getTime()
  let betweenTime = 0
  // 还没开始 相差时间为负数
  if (newTime < startTime) {
    betweenTime = newTime - startTime
  } else {
    // 还没结束
    betweenTime = endTime - newTime
  }
  return betweenTime
}

/**
 * 日期转时间戳
 */
export const dateToTimestamp = (dateStr) => {
  if (!dateStr) {
    return ''
  }
  const newDataStr = dateStr.replace(/\.|-/g, '/')
  const date = new Date(newDataStr)
  const timestamp = date.getTime()
  return timestamp
}

/**
 * 改变日期
 */
export const tsToDate = (number, format) => {
  const formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
  const returnArr = []
  const date = new Date(number)
  returnArr.push(date.getFullYear())
  returnArr.push(timeFormat(date.getMonth() + 1))
  returnArr.push(timeFormat(date.getDate()))
  returnArr.push(timeFormat(date.getHours()))
  returnArr.push(timeFormat(date.getMinutes()))
  returnArr.push(timeFormat(date.getSeconds()))
  for (const i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i])
  }
  return format
}

/**
 * 价格处理
 */
export const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

/**
 * 手机号正则校验
 */
export const checkPhoneNumber = (phoneNumber) => {
  const regexp = /^[1][0-9]{10}$/
  return regexp.test(phoneNumber)
}

/**
 * 用户名正则校验
 */
export const checkUserName = (userName) => {
  const regexp = /^([a-zA-Z0-9_]{4,16})$/
  return regexp.test(userName)
}

/**
 * 修改 favicon 图标
 */
export const changeFavicon = () => {
  const webConfigStore = useWebConfigStore()
  const link = webConfigStore.pcConfig.pcTitleImg || ''
  if (!link) {
    return
  }
  let favicon = document.querySelector('link[rel="icon"]')
  if (favicon !== null) {
    favicon.href = link
  } else {
    favicon = document.createElement('link')
    favicon.rel = 'icon'
    favicon.href = link
    document.head.appendChild(favicon)
  }
}

/**
 * 请求系统支付开关
 * @param {Boolean} forcedRefresh 是否强制刷新数据
 * @param {Function} fn 回调
 */
export const getSysPaySwitch = (forcedRefresh, fn) => {
  // 获取缓存中的配置
  const paySwitchInfo = JSON.parse(localStorage.getItem('bbcPaySwitchInfo')) || {}
  if (!paySwitchInfo.expiredTime || new Date().getTime() > paySwitchInfo.expiredTime || forcedRefresh) {
    http({
      url: '/sys/config/info/getSysPaySwitch',
      methods: 'get'
    }).then(({ data }) => {
      const paySwitchInfo = {
        switchInfo: data,
        expiredTime: 5 * 60 * 60 * 1000 + new Date().getTime()
      }
      localStorage.setItem('bbcPaySwitchInfo', JSON.stringify(paySwitchInfo))
      if (fn) fn()
    })
  }
}

// 检查是否开启支付方式
export const checkPayWay = (paySwitchInfo) => {
  let notAvailable = true
  for (const payKey in paySwitchInfo) {
    if (paySwitchInfo[payKey]) {
      notAvailable = false
      break
    }
  }
  if (notAvailable) {
    ElMessageBox.confirm('抱歉，无可用付款方式', $t('tips'), {
      distinguishCancelAndClose: true,
      confirmButtonText: $t('determine'),
      cancelButtonText: $t('cancel')
    })
  }
  return !notAvailable
}

/**
 * 防抖
 */
export function _debounce (fn, delay = 200) {
  let timer
  return function () {
    const th = this
    const args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function () {
      timer = null
      fn.apply(th, args)
    }, delay)
  }
}

/**
 * 防抖2.0
 */
export function debounce (fn, t) {
  const delay = t || 1000
  let timer
  return function () {
    const args = arguments
    if (timer) {
      clearTimeout(timer)
    }

    const callNow = !timer

    timer = setTimeout(() => {
      timer = null
    }, delay)

    if (callNow) fn.apply(this, args)
  }
}

/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export function _throttle (fn, interval = 500) {
  let last
  let timer
  return function () {
    const args = arguments
    const now = +new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        last = now
        fn.apply(this, args)
      }, interval)
    } else {
      last = now
      fn.apply(this, args)
    }
  }
}

export const addUrlParam = (url, key, value) => {
  if (!value) {
    return url
  }
  const re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i')
  const separator = url.indexOf('?') !== -1 ? '&' : '?'
  if (url.match(re)) {
    return url.replace(re, '$1' + key + '=' + value + '$2')
  } else {
    return url + separator + key + '=' + value
  }
}

/**
 * 精度运算
 * @param {*} a 第一个计算数(例如:被除数/被减数)
 * @param {*} b 第二个计算数(例如:除数/减数)
 * @param {*} countMode 计算方式(0:加 1:减 2:乘 3:除)
 */
export function accuracyCount (a, b, countMode) {
  let finalResult = 0
  if (countMode === 0) {
    finalResult = new Big(a).plus(b).valueOf()
  } else if (countMode === 1) {
    finalResult = new Big(a).minus(b).valueOf()
  } else if (countMode === 2) {
    finalResult = new Big(a).times(b).valueOf()
  } else if (countMode === 3) {
    finalResult = new Big(a).div(b).valueOf()
  } else {
    return
  }
  return finalResult
}
/**
* 文件地址校验
* @param fileUrl 获取到的文件路径
*/
export function checkFileUrl (fileUrl) {
  if (fileUrl === '') return ''
  const baseUrl = import.meta.env.VITE_APP_RESOURCES_URL
  // 适配el-image 图片组件预览功能
  if (fileUrl && typeof fileUrl === 'object') {
    // eslint-disable-next-line no-return-assign
    return fileUrl.map(el => el = checkFileUrl(el))
  } else {
    if (fileUrl && fileUrl.indexOf('http') === -1) {
      return baseUrl + fileUrl
    } else {
      return fileUrl
    }
  }
}
